package com.atwisdom.star.core.bsl.dataSource;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import com.atwisdom.star.common.util.SpringContextUtil;
import com.atwisdom.star.config.DynamicDataSource;
import com.atwisdom.star.core.dao.service.TenantInfoService;
import com.atwisdom.star.core.dsl.modelClass.resource.ResourceInstanceDslService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源初始化
 */
@Slf4j
// @Configuration
@AllArgsConstructor
public class DynamicDataSourceInit {

    private TenantInfoService tenantInfoService;
    private ResourceInstanceDslService resourceInstanceDslService;

    @Bean
    public void initDataSource() {
        log.info("======初始化动态数据源=====");
        DynamicDataSource dynamicDataSource =  SpringContextUtil.getBean("dynamicDataSource");
        DruidDataSource master = SpringContextUtil.getBean("master");
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("master", master);

        String condition = "status = 1";
        String className = "system_project";
        List<JSONObject> tenantJsonList = resourceInstanceDslService.query(condition, className, null);
        if (CollectionUtil.isNotEmpty(tenantJsonList)) {
            tenantJsonList.forEach(d->{
                JSONObject values = d.getJSONObject("values");
                log.info("tenant = {}", values.toString());
                DruidDataSource dataSource = new DruidDataSource();
                dataSource.setDriverClassName(values.getString("datasource_driver"));
                dataSource.setUrl(values.getString("datasource_url"));
                dataSource.setUsername(values.getString("datasource_username"));
                dataSource.setPassword(values.getString("datasource_password"));
                dataSource.setConnectProperties(master.getConnectProperties());
                if (StrUtil.isNotBlank(values.getString("tenant_id"))) {
                    dataSourceMap.put(values.getString("tenant_id"), dataSource);
                }
            });
        }
        dynamicDataSource.setDataSources(dataSourceMap);
        dynamicDataSource.afterPropertiesSet();
    }
}
